package com.inspur.ydt.service.impl;

import java.util.Map;

//import org.apache.logging.log4j.LogManager;
//import org.apache.logging.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;
import com.inspur.iop.model.PostParameter;
import com.inspur.ydt.bean.HousingFundTemplate;
import com.inspur.ydt.bean.PersonalUrls;
import com.inspur.ydt.service.PersonalService;
import com.inspur.ydt.util.RequestUtils;

@Service("personalService26")
public class PersonalServiceImpl implements PersonalService {

//	static Logger logger = LogManager.getLogger(PersonalServiceImpl.class.getName());
	//公积金请求参数名
	private static final String HOUSING_FUND_KEY = "xmlparam";
	//公积金加密标识  0：表示不加密，1：表示加密
	private static final String EDIV = "0";
	
	@Override
	public Object housingFund(Map<String, String> paramsMap) {
		//公积金请求报文
		String xmlparam = generateHousingFundParameter(paramsMap);
		//生成请求参数
		PostParameter[] postparams = RequestUtils.generatePostParameters(HOUSING_FUND_KEY , xmlparam);
		String result = RequestUtils.requestInfo(PersonalUrls.HOUSING_FUND_CONTENT,
				PersonalUrls.HOUSING_FUND_VERSION, postparams);
//		logger.info("visitResult: "+result);
		return result;
	}
	
	@Override
	public Object getPersonalInfoById(String idKeyName, String idNumber, String url, String version) {
		//生成请求参数
		PostParameter[] postparams = RequestUtils.generatePostParameters(idKeyName , idNumber);
		String result = RequestUtils.requestInfo(url, version, postparams);
//		logger.info("visitResult: "+result);
		return result;
	}
	
	@Override
	public Object getPersonalInfoByIdAndDate(String idKeyName, String idNumber, String dateStartKeyName,
			String dateStart, String dateEndKeyName, String dateEnd, String url, String version) {
		//生成请求参数
		PostParameter[] postparams = RequestUtils.generatePostParameters(idKeyName , idNumber,
				dateStartKeyName, dateStart, dateEndKeyName, dateEnd);
		String result = RequestUtils.requestInfo(url, version, postparams);
//		logger.info("visitResult: "+result);
		return result;
	}
	
	/**
	 * 生成公积金查询报文
	 * @param parameterMap
	 * @return
	 */
	public String generateHousingFundParameter(Map<String, String> parameterMap) {
		Document document = null;
		try {
			document = DocumentHelper.parseText(new String(HousingFundTemplate.getBytes(), HousingFundTemplate.DEFAULT_CHARSET));
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
			String key = entry.getKey();
			Element element;
			//姓名和省份证证号在 root -> body 路径下
			if ("name".equals(key) || "ceridnum".equals(key)) {
				element = document.getRootElement().element("body").element(key);
			} else { //其余在 root -> head 路径下
				element = document.getRootElement().element("head").element(key);
			}
			//模板有此节点并且值非空
			if (element != null && entry.getValue() != null) {
				element.setText(entry.getValue().trim());
			}
		}
//		logger.info("visitResult: "+AddPacketLengthAndIsEncrypted(document.asXML()));
		return AddPacketLengthAndIsEncrypted(document.asXML());
	}
	
	/**
	 * 将报文前部按要求格式拼接出来 -- 添加报文长度（8位）和是否加密标志位（1位）
	 * @param strXml 拼接报文头前的报文
	 * @param EDIV 加密标识 0：表示不加密，1：表示加密
	 * @return
	 * @see String 拼接报文头后的报文
	 */
	private String AddPacketLengthAndIsEncrypted(String strXml) {
		return formatLength(String.valueOf(strXml.length()), 8) + EDIV + strXml;
	}

	/**
	 * 获取报文长度，并格式化为定长八位，左侧补0的字符串 
	 * @param code 报文实际长度数值
	 * @param num 报文头要求的总长度
	 * @return String 按要求格式化后的报文头
	 */
	private String formatLength(String code, int num) {
		String result = "";
		result = String.format("%0" + num + "d", Integer.parseInt(code) + 1);
		return result;
	}


}
